import { createVNode, render, ref, computed } from 'vue'
import { ElProgress } from 'element-plus'
import 'element-plus/dist/index.css'
import event from '../../eventCenter/index'

// 创建进度条容器
const progressContainer = document.createElement('div')
document.body.appendChild(progressContainer)

// 响应式状态管理
const downloadPercent = ref(0)
const isShow = ref(false)
const isPreparing = ref(false) // 准备状态标识
let progressData = { loaded: 0, total: 0 } // 进度数据

// 计算进度条状态
const progressStatus = computed(() => {
  if (downloadPercent.value === 100) return 'success'
  return ''
})

// 创建虚拟DOM渲染函数
const renderProgress = () => {
  // 准备阶段：旋转加载
  if (isPreparing.value) {
    const vnode = createVNode(
      'div',
      {
        class: 'global-progress-mask',
        style: { display: isShow.value ? 'flex' : 'none' }
      },
      [
        createVNode('div', { class: 'progress-container' }, [
          createVNode('div', { class: 'spinner-wrapper' }, [createVNode('div', { class: 'spinner' })]),
          createVNode('p', { class: 'status-text' }, '准备下载中...')
        ])
      ]
    )
    render(vnode, progressContainer)
    return
  }

  // 下载阶段：进度条
  const vnode = createVNode(
    'div',
    {
      class: 'global-progress-mask',
      style: { display: isShow.value ? 'flex' : 'none' }
    },
    [
      createVNode('div', { class: 'progress-container' }, [
        createVNode('div', { class: 'progress-wrapper' }, [
          createVNode(ElProgress, {
            type: 'circle',
            percentage: downloadPercent.value,
            strokeWidth: 5,
            width: 90,
            status: progressStatus.value,
            format: percentage => `${percentage}%`
          })
        ]),
        createVNode(
          'p',
          { class: 'status-text' },
          `${formatFileSize(progressData.loaded)} / ${formatFileSize(progressData.total)}`
        )
      ])
    ]
  )
  render(vnode, progressContainer)
}

// 辅助函数：格式化文件大小显示
const formatFileSize = bytes => {
  if (!bytes) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 初始化事件监听
const initProgressListener = () => {
  event.on('blobload', () => {
    isPreparing.value = true
    isShow.value = true
    downloadPercent.value = 0
    progressData = { loaded: 0, total: 0 }
    renderProgress()
  })

  event.on('downloadProgress', data => {
    progressData = data
    if (isPreparing.value) {
      isPreparing.value = false
    }
    downloadPercent.value = Math.max(0, Math.min(100, data.percent))
    isShow.value = true
    renderProgress()

    if (downloadPercent.value === 100) {
      setTimeout(() => {
        isShow.value = false
        isPreparing.value = false
        downloadPercent.value = 0
        renderProgress()
      }, 800)
    }
  })

  event.on('downloadError', () => {
    isShow.value = false
    isPreparing.value = false
    downloadPercent.value = 0
    renderProgress()
  })
}

// 样式优化：精确控制尺寸
const style = document.createElement('style')
style.textContent = `
  .global-progress-mask {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    backdrop-filter: blur(2px);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 9999;
    transition: opacity 0.3s ease;
  }

  /* 核心：固定容器尺寸和内边距 */
  .progress-container {
    background: #fff;
    padding: 20px;
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12px;
    width: 160px; /* 固定宽度 */
    height: 160px; /* 固定高度 */
    box-sizing: border-box; /* 确保padding不影响整体尺寸 */
  }

  /* 旋转动画容器：与进度条容器尺寸一致 */
  .spinner-wrapper, .progress-wrapper {
    width: 90px;
    height: 90px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  /* 旋转动画 */
  .spinner {
    width: 80px;
    height: 80px;
    border: 4px solid #f3f3f3;
    border-top: 4px solid #409eff;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }

  /* 统一文本样式 */
  .status-text {
    margin: 0;
    color: #606266;
    font-size: 14px;
    text-align: center;
    line-height: 1.4;
    width: 100%; /* 文本宽度填满容器 */
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }
`
document.head.appendChild(style)

// 插件安装
export default {
  install: app => {
    renderProgress()
    initProgressListener()

    app.config.globalProperties.$downloadProgress = {
      show: () => {
        isShow.value = true
        renderProgress()
      },
      hide: () => {
        isShow.value = false
        isPreparing.value = false
        renderProgress()
      },
      setPercent: percent => {
        isPreparing.value = false
        downloadPercent.value = percent
        renderProgress()
      },
      setPreparing: () => {
        isPreparing.value = true
        isShow.value = true
        renderProgress()
      }
    }
    app.provide('downloadProgress', app.config.globalProperties.$downloadProgress)
  }
}
